package com.sd365.permission.centre.service.impl;/*
用户
@author 
@date 2022/12/19 14：17
**/

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sd365.common.core.annotation.stuffer.IdGenerator;
import com.sd365.common.core.common.aop.MyPageInfo;
import com.sd365.common.core.common.exception.BusinessException;
import com.sd365.common.core.common.exception.DataBaseException;
import com.sd365.common.core.common.exception.code.BusinessErrorCode;
import com.sd365.common.core.context.BaseContextHolder;
import com.sd365.common.util.BeanUtil;
import com.sd365.common.util.DateUtil;
import com.sd365.permission.centre.dao.mapper.*;
import com.sd365.permission.centre.entity.*;
import com.sd365.permission.centre.pojo.dto.RoleDTO;
import com.sd365.permission.centre.pojo.dto.UserDTO;
import com.sd365.permission.centre.pojo.dto.pcp.PcpUserDTO;
import com.sd365.permission.centre.pojo.dto.shop.ShopBuyerDTO;
import com.sd365.permission.centre.pojo.query.UserQuery;
import com.sd365.permission.centre.service.UserService;
import com.sd365.permission.centre.service.util.Md5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserServiceImpl extends AbstractBaseDataServiceImpl implements UserService {
    @javax.annotation.Resource
    UserMapper userMapper;
    @javax.annotation.Resource
    UserRoleMapper userRoleMapper;
    UserRole userRole;
    @javax.annotation.Resource
    RoleMapper roleMapper;
    @javax.annotation.Resource
    DepartmentMapper departmentMapper;
    @javax.annotation.Resource
    PositionMapper positionMapper;
    @Autowired
    private IdGenerator idGenerator;
    @javax.annotation.Resource
    RoleResourceMapper roleResourceMapper;
    @javax.annotation.Resource
    ResourceMapper resourceMapper;
    @Override
    @Transactional(rollbackFor = DataBaseException.class)
    public Boolean add(UserDTO userDTO) {
        if (userDTO==null||userDTO.getEmail()==null||userDTO.getCode()==null||userDTO.getPassword()==null){
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("参数错误"));
        }
        List<User> users=userMapper.selectAll();
            for (User user:users){
                if(user.getCode().equals(userDTO.getCode())){
                    throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("code已经被使用"));
                }
            }
        UserRole userRole1;
        List<RoleDTO> roleDTOS=userDTO.getRoleList();
        User user= BeanUtil.copy(userDTO,User.class);
        user.setId(idGenerator.snowflakeId());
        Date date= DateUtil.getCurrentDate();
        user.setCreatedTime(date);
        user.setUpdatedTime(date);
        if (userDTO.getCreatedBy()==null){
            user.setCreatedBy(1337970508645400576L);
        }
        if(userDTO.getUpdatedBy()==null){
            user.setUpdatedBy(1337970508645400576l);
        }
        user.setPassword(Md5Utils.digestHex(userDTO.getPassword()));
        user.setVersion(1l);
        user.setStatus((byte) 1);
        if(roleDTOS!=null){
        List<Role> roleList=BeanUtil.copyList(roleDTOS,Role.class);
        user.setRoleList(roleList);
        }else {
            user.setRoleList(null);
        }
        if(userMapper.insert(user)<=0){
           throw new DataBaseException();
        }else {
                if(user.getRoleList()!=null){
                    List<Role> roles=user.getRoleList();
                    for (Role role:roles){
                        if(roleMapper.selectById(role.getId())!=null) {
                            userRole1 = BeanUtil.copy(user, UserRole.class);
                            userRole1.setUserId(user.getId());
                            userRole1.setRoleId(role.getId());
                            userRole1.setId(idGenerator.snowflakeId());
                            if(userRoleMapper.insert(userRole1)<=0){
                                throw new DataBaseException();
                            }
                        }
                    }
                }
            return true;
        }
    }

    @Override
    @Transactional(rollbackFor = DataBaseException.class)
    public Boolean remove(Long id, Long version) {
        if (id == null || version == null) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("参数为空"));
        }
        if (userMapper.selectById(id) == null) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("没有该用户"));
        }
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("id", id).andEqualTo("version", version);
        if (!userRoleMapper.selectByUserId(id).isEmpty()) {
            if (userRoleMapper.deleteAllByUserID(id) <= 0) {
                throw new DataBaseException();
              }
            }
        if (userMapper.deleteByExample(example) >0) {
            return true;
        }else {
            throw new DataBaseException();
        }

    }
    @Override
    public Boolean modify(UserDTO userDTO) {
        if(userDTO==null||userDTO.getEmail()==null||userDTO.getCode()==null||userDTO.getPassword()==null||userDTO.getCreatedTime()==null){
            throw  new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("参数为空"));
        }
        if(userMapper.selectById(userDTO.getId())==null){
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("没有该角色请确认id是否正确"));

        }
        User user1=userMapper.selectById(userDTO.getId());
        List<User> users=userMapper.selectAll();
        if(!user1.getCode().equals(userDTO.getCode())){
        for (User user:users){
            if(user.getCode().equals(userDTO.getCode())){
                throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("code已经被使用"));
            }
        }}
        List<RoleDTO> roleDTOS=userDTO.getRoleList();
        User user= BeanUtil.copy(userDTO,User.class);
        List<Role> roleList=BeanUtil.copyList(roleDTOS,Role.class);
        user.setRoleList(roleList);
        if(!userRoleMapper.selectByUserId(user.getId()).isEmpty()){
            if(userRoleMapper.deleteAllByUserID(user.getId())<=0){
             throw new DataBaseException();
            }
        }
        if(!roleDTOS.isEmpty()||roleDTOS.size()>1){
        for (Role role:roleList){
            if(roleMapper.selectById(role.getId())==null){
                throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("包含没有的角色"));
            }
            UserRole userRole1=BeanUtil.copy(user,UserRole.class);
            userRole1.setId(idGenerator.snowflakeId());
            userRole1.setUserId(user.getId());
            userRole1.setRoleId(role.getId());
            userRole1.setUpdatedTime(DateUtil.getCurrentDate());
            userRole1.setUpdatedBy(1337970508645400576l);
            if(userRoleMapper.insert(userRole1)<=0){
                throw new DataBaseException();
            }
        }}
        Date date=DateUtil.getCurrentDate();
        user.setUpdatedTime(date);
        if(userMapper.update(user)<=0){
           throw new DataBaseException();
        } return true;
    }

    @Override
    @Transactional(rollbackFor = DataBaseException.class)
    public Boolean modifyWithNewRole(UserDTO[] userDTOS) {
        if(userDTOS==null||userDTOS.length<1){
            throw  new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("参数为空"));
        }
       for (UserDTO userDTO:userDTOS){
           if(userDTO==null||userDTO.getVersion()==null||userDTO.getCode()==null||userDTO.getCreatedBy()==null||userDTO.getCreatedTime()==null){
               throw  new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("包含空对象"));

           }
           if(userMapper.selectById(userDTO.getId())==null){
               throw  new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception(",没有该用户"+userDTO));
           }
           User user2=userMapper.selectById(userDTO.getId());
          List<RoleDTO> roleDTOS=userDTO.getRoleList();
          if(roleDTOS==null){
              throw  new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("角色列表不能为空"));
          }
          if(!user2.getCode().equals(userDTO.getCode())){
          User user=userMapper.selectByCode(userDTO.getCode());
            if(user!=null){
               throw  new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("code已被使用"));
            }}
          if(roleDTOS.size()<1){
              throw  new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("至少包含一个角色对象"));
          }
                 userRole=BeanUtil.copy(userDTO,UserRole.class);
                 if(userRoleMapper.selectByUserId(userDTO.getId())!=null){
                    if( userRoleMapper.deleteAllByUserID(userDTO.getId())<=0){
                        throw new DataBaseException();
                    }
                 }
                for (RoleDTO roleDTO:roleDTOS){
                    if(roleDTO==null){
                        continue;
                    }
                    if(roleMapper.selectById(roleDTO.getId())==null){
                        throw  new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("没有角色"+roleDTO));
                    }
                    userRole.setRoleId(roleDTO.getId());
                    userRole.setId(idGenerator.snowflakeId());
                    userRole.setUserId(userDTO.getId());
                    userRole.setUpdatedTime(DateUtil.getCurrentDate());
                    userRole.setCreatedBy(1337970508645400576l);
                    userRole.setCreatedTime(DateUtil.getCurrentDate());
                    if(userRoleMapper.insert(userRole)<=0){
                        throw new DataBaseException();
                    }
                }
        }return  true;
    }

    @Override
    public List<User> commonQuery(UserQuery userQuery) {
        List<User> users = new ArrayList<>();
        User user=BeanUtil.copy(userQuery,User.class);
        if(userQuery.getRoleId()==null){
        PageHelper.startPage(userQuery.getPageNum(), userQuery.getPageSize());
         users = userMapper.commonQuery(user);
        for (User user1:users){
            user1.setRoleList(roleMapper.selectRoleByUserid(user1.getId()));
        }}else {
            Example example = new Example(UserRole.class);
            example.createCriteria().andEqualTo("roleId", userQuery.getRoleId());
            PageHelper.startPage(userQuery.getPageNum(), userQuery.getPageSize());
            List<UserRole> userRoles=userRoleMapper.selectByExample(example);
            users= BeanUtil.copyList(userRoles, User.class);
            for (User user1:users){
                for(UserRole userRole1:userRoles){
               User user2=userMapper.selectById(userRole1.getUserId());
               user1.setCompany(user2.getCompany());
               user1.setRoleList(roleMapper.selectRoleByUserid(userRole1.getUserId()));
               user1.setUpdatedTime(user2.getUpdatedTime());
               user1.setCode(user2.getCode());
               user1.setOrganization(user2.getOrganization());
               user1.setName(user2.getName());
               user1.setBirthday(user2.getBirthday());
               user1.setDepartment(user2.getDepartment());
               user1.setDepartmentId(user2.getDepartmentId());
               user1.setPassword(user2.getPassword());
               user1.setTenantId(user2.getTenantId());
               user1.setPosition(user.getPosition());
               user1.setPositionId(user2.getPositionId());
               user1.setTel(user2.getTel());}
            }
        }
       if (!users.isEmpty()) {
                Page page=(Page) users;
                BaseContextHolder.set("pageInfo", JSON.toJSONString(new MyPageInfo(page.getTotal(), page.getPages())));
                return users;
            } else {
                throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("暂时没有用户"));
            }
        }

    @Override
    public User queryById(Long id) {
        if(id==null){
            throw  new BusinessException();
        }
        User user= userMapper.selectById(id);
        if (user!=null){
         Example example=new Example(UserRole.class);
         example.createCriteria().andEqualTo("userId",id);
         List<UserRole> userRoles=userRoleMapper.selectByExample(example);
         List<Role> roles=new ArrayList<>();
         if(!userRoles.isEmpty()){
         for (UserRole userRole1:userRoles){
            Role role=roleMapper.selectById(userRole1.getRoleId());
            roles.add(role);
         }
         user.setRoleList(roles);
        } return  user;}else  throw  new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("没有用户"));
    }

    @Override
    public List<Role> queryAllRole() {
         List<Role> roles=roleMapper.selectAll();
         return roles;
    }

    @Override
    public List<Department> queryAllDepartment() {
        List<Department> departments=departmentMapper.selectAll();
        return  departments;
    }

    @Override
    public List<Position> queryAllPosition() {
        List<Position> positions= positionMapper.selectAll();
        return  positions;
    }

    @Override
    @Transactional(rollbackFor = DataBaseException.class)
    public Boolean batchUpdate(UserDTO[] userDTOS) {
        if(userDTOS==null){
            throw  new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("参数为空"));
        }
            for (UserDTO userDTO:userDTOS){
                if(userMapper.selectById(userDTO.getId())==null){
                    throw  new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("参数有误，没有该用户"+userDTO));
                }User user=userMapper.selectById(userDTO.getId());
                user.setUpdatedTime(DateUtil.getCurrentDate());
                user.setUpdatedBy(1337970508645400576l);
                user.setStatus(userDTO.getStatus());
                Example example=new Example(User.class);
                example.createCriteria().andEqualTo("id",user.getId());
                if(userMapper.updateByExample(user,example)<=0){
                   throw  new DataBaseException();
                }
            }
           return true;
        }

    @Override
    @Transactional(rollbackFor = DataBaseException.class)
    public Boolean batchDelete(UserDTO[] userDTOS) {
        if(userDTOS!=null){
            for (UserDTO userDTO:userDTOS){
                if(userDTO==null){
                    continue;
                }
                if(userDTO.getCode()==null&&userDTO.getDepartmentId()==null&&userDTO.getName()==null&&userDTO.getVersion()==null){
                    throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("校验参数为空"));
                }
                User user=BeanUtil.copy(userDTO,User.class);
                if(userMapper.selectById(user.getId())!=null){
                    if (!userRoleMapper.selectByUserId(user.getId()).isEmpty()) {
                        if (userRoleMapper.deleteAllByUserID(user.getId()) <= 0) {
                            throw new DataBaseException();
                        }
                    }
                    Example example=new Example(User.class);
                    example.createCriteria().andEqualTo("id",userDTO.getId());
                if(userMapper.deleteByExample(example)<=0){
                    throw  new DataBaseException();
                }
            }else {
                    throw  new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("参数有误，没有该用户"+userDTO));
                }

            }
            return true;
        }else {
            throw  new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("参数为空"));
        }
    }

    @Override
    public Boolean firstStartMd5() {
        List<User> userList=userMapper.selectAll();
        for (User user:userList){
        String encode = new String(MD5Encoder.encode(user.getPassword().getBytes()));
        BaseContextHolder.set(String.valueOf(user.getName()),encode);
        }
        return true;
    }

    @Override
    public Boolean pcpUserRegister(List<PcpUserDTO> pcpUserDTOS) {
        if(pcpUserDTOS==null){
            throw new BusinessException();
        }
       try {
           for (PcpUserDTO pcpUserDTO:pcpUserDTOS){
               User user=BeanUtil.copy(pcpUserDTO,User.class);
               if(userMapper.insert(user)<=0){
                   throw new DataBaseException();
               }
           }
           return true;
       } catch (Exception e){
           log.error(""+e);
           return false;
       }
    }


    @Override
    public Boolean pcpUserUpdate(List<PcpUserDTO> pcpUserDTOS) {
        if(pcpUserDTOS==null){
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("参数错误"));
        }
        try {
            for (PcpUserDTO pcpUserDTO:pcpUserDTOS){
                User user=BeanUtil.copy(pcpUserDTO,User.class);
                if(userMapper.update(user)<=0){
                    throw new DataBaseException();
                }
            }
            return true;
        } catch (Exception e){
            log.error(""+e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUserLockStatus(List<PcpUserDTO> pcpUserDTOS) {
        if(pcpUserDTOS==null){
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("参数错误"));
        }
            for (PcpUserDTO pcpUserDTO:pcpUserDTOS){
                User user=BeanUtil.copy(pcpUserDTO,User.class);
                if(userMapper.update(user)<=0){
                    throw new DataBaseException();
                }
            }
            return true;
    }

    @Override
    public Boolean shopUserRegister(List<ShopBuyerDTO> shopBuyerDTOS) {
        if(shopBuyerDTOS==null){
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("参数错误"));
        }
        try {
            for (ShopBuyerDTO shopBuyerDTO:shopBuyerDTOS){
                User user=BeanUtil.copy(shopBuyerDTO,User.class);
                if(userMapper.insert(user)<=0){
                    throw new DataBaseException();
                }
            }
            return true;
        } catch (Exception e){
            log.error(""+e);
            return false;
        }
    }

    @Override
    public Boolean updatePassword(UserDTO userDTO) {
        if(userDTO==null){
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("参数为空"));
        }
         User user=BeanUtil.copy(userDTO,User.class);
         if(userMapper.update(user)>0){
           return true;
       }else return false;
    }

      @Override
      public User getUser(String code) {
        if (code==null){
          throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("参数为空"));
        }
      User user=userMapper.selectByCode(code);
      if(user!=null){
          return user;
      }else {
          log.error("查询失败");
          return  null;
            }
      }
      @Override
      public  List<Resource>  getUserResource(Long id){
        if(id==null){
            throw  new BusinessException();
        }
        List<Role>roles= roleMapper.selectRolesByUserId(id);
        List<RoleResource> roleResources=new ArrayList<>();
        for (Role role:roles){
            Example example=new Example(RoleResource.class);
            example.createCriteria().andEqualTo("RoleId",role.getId());
            List<RoleResource>  roleResourceList=roleResourceMapper.selectByExample(example);
            for (RoleResource roleResource:roleResourceList){
                roleResources.add(roleResource);
            }
        }
        List<Resource> resources=new ArrayList<>();
        List<Long> resourceIds=new ArrayList<>();
        for (RoleResource roleResource:roleResources){
            resourceIds.add(roleResource.getResourceId());
        }
        resources.stream()
                .distinct()
                .collect(Collectors.toList());
        for (Long resourceId:resourceIds){
          resources.add(resourceMapper.findById(resourceId));
        }
         return  resources;

    }
}
